<?php
/*
	
*/
defined('BY_JYA') or exit('Access Denied');
global $_RQ,$_AR;
$_RQ['op']=$_RQ['op']?$_RQ['op']:'confirm';
$return=array();
$return['diy']=$this->plugin_setting('diy');
$return['basic']=$this->plugin_setting('basic');
if($_RQ['op']=='confirm'){
	$this->model('order')->check_level();
	$mid = $_SESSION['uid'];
	$uniacid = $_SESSION['uniacid'];
	$isverify = false;
	$goodsid = intval($_RQ['goodsid']);
	$groupid = intval($_RQ['groupid']);
	$type = $_RQ['type']?:'groups';
	$heads = intval($_RQ['heads']);
	$teamid = intval($_RQ['teamid']);
	if($teamid){
		$team=pdo_get('jy_aligroup_groups_team',array('uniacid'=>$_SESSION['uniacid'],'id'=>$teamid));
		$goodsid=$team['goodsid'];
		$groupid=$team['groupid'];
	}
	$member = pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$mid));
	$credit = array();
	$group=pdo_get('jy_aligroup_groups',array('uniacid'=>$_SESSION['uniacid'],'id'=>$groupid));
	if($group['goodsid']){
		$goods = pdo_get('jy_weishop_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$group['goodsid']));
	}
	if ($goods['total'] <= 0) {
			exi('您选择的商品已经下架，请浏览其他商品或联系商家！','error','jy_aligroup/myteam/');
	}
	$ordernum = pdo_count('jy_aligroup_groups_order',array('status' => array(1,2,3,4), 'groupid' => $groupid, 'uniacid' => $uniacid));
	//改商品限制目前无效
	if (!(empty($group['goodsnum'])) && ($group['goodsnum'] <= $ordernum)) {
		exi('已到达此商品拼团参与上限，请浏览其他商品或联系商家！','error');
	}
	$order = pdo_get('jy_aligroup_groups_order',array('mid' => $mid,'is_team'=>1,'status' =>array(0,1),'groupid' => $groupid, 'uniacid' => $uniacid));
	if ($order && ($order['status'] == 0)) {
		exi('您的订单已存在，请尽快完成支付！','error','jy_aligroup/order/getlist/');
	}
	if ($order && ($order['status'] == 1)) {
			exi('您已经参与了该团，请等待拼团结束后再进行购买！','error','jy_aligroup/myteam/');
	}
	if ($teamid) {
			$groupnum = pdo_count('jy_aligroup_groups_order',array('status' => array(1,2,3,4),'teamid' => $teamid, 'groupid' => $groupid, 'uniacid' => $uniacid));
			if ($group['groupnum'] <= $groupnum) {
					exi('该团人数已成团，请参与其他团！','error','jy_aligroup/myteam/');
			}
			$team = pdo_get('jy_aligroup_groups_team',array('id' => $teamid,'groupid' => $groupid,'uniacid' => $uniacid));
			if ($team['status'] == 2) {
					exi('该团已过期，请参与其他团队！','error','jy_aligroup/group/');
			}
			if ($team['status'] == 1) {
					exi('该团已完成，请参与其他团队！','error','jy_aligroup/group/');
			}
	}
	//首次开团增加一个以该用户为团长的团
	if($type == 'groups' && empty($teamid)&& $heads==1 && empty($order)){
		//判断团长是否是首次开团
		$hasteam=pdo_get('jy_aligroup_groups_team',array('uniacid'=>$_SESSION['uniacid'],'status'=>0,'groupid'=>$groupid,'headsid'=>$_SESSION['uid']));
		if(empty($hasteam)){
		}else{
				exi('您已经开过该团，请先完成拼团！','error','jy_aligroup/myteam/');
		}
	}
	if ($type == 'groups') {
			if(!$group['feetype'] && $group['agio']!=0){
				$goods['groupsprice'] = $group['agio']*$goods['price']/100;
			}elseif($group['feetype'] && $group['price']!=0){
				$goods['groupsprice'] = $group['price'];
			}else{
				$goods['groupsprice'] = $goods['price'];
			}
			$goodsprice = $goods['groupsprice'];
			$price = $goods['groupsprice'];
			$groupnum = intval($goods['groupnum']);
			$is_team = 1;
	}else if ($type == 'single') {
			$goodsprice = $goods['singleprice'];
			$price = $goods['singleprice'];
			$groupnum = 1;
			$is_team = 0;
			$teamid = 0;
	}
	//团长优惠
	if($group['isdiscount']==1 && $heads==1){		
			if($group['headstype']==1){
				$goods['headsmoney'] = $group['headsmoney'];
			}else{
				$goods['headsmoney'] = $goods['groupsprice']*$group['headsdiscount']/100;
			}
	}
	
	if($goods['headsmoney']>0){
		$price = $price - $goods['headsmoney'];
	}
	if ($price < 0) {
		$price = 0;
	}
	$item=array();
	if ($goods['isverify'] || $goods['type']) {
			$isverify = true;
			$goods['freight'] = 0;
			$storeids = array();
			$merchid = 0;
			if (!(empty($goods['storeids']))) {
				$merchid = $goods['merchid'];
				$storeids =json_decode($goods['storeids'],true);
				$ids =array();
				 foreach($storeids as $item){
					$ids[]=$item['id'];
				 }
			}
			$params=array('uniacid' => $_SESSION['uniacid'],'status'=>1,'type'=>array(2,3));
			if (empty($storeids)) {
				if (0 < $merchid) {
					$params['merchid']=$merchid;
				}
			}else if (0 < $merchid) {
				$params['merchid']=$merchid;
				if($ids){
					$params['id']=$ids;
				}
			} else {
				if($ids){
					$params['id']=$ids;
				}
			}
			$stores = pdo_getall('jy_weishop_store',$params);
			$verifycode = 'PT' . random(8, true);
			while (1) {
				$count = pdo_fetchcolumn('select count(*) from ' . tablename('jy_aligroup_groups_order') . ' where verifycode=:verifycode and uniacid=:uniacid limit 1', array(':verifycode' => $verifycode, ':uniacid' => $_SESSION['uniacid']));
				if ($count <= 0) {
					break;
				}
				$verifycode = 'PT' . random(8, true);
			}
			((!(empty($goods['verifytype'])) ? $verifynum = $goods['verifynum'] : 1));
			$item['sendtype']=2;
		}else {
			//会员默认地址
			$address =  pdo_get('core_address',array('mid'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid'],'isdefault'=>1));
			$item['sendtype']=1;
		}
		$goods['freight'] = $goods['freight']?$goods['freight']:0;
		$group['sendtype']=1;
		/*
		//整理收货地址信息
		$member_address=pdo_getall('core_address',array('mid'=>$_SESSION['uid']));
		if($member_address){
			foreach($member_address as &$address){
				$address['pcd']=json_decode($address['pcd'],true);
				if($address['isdefault']){
					$group['addressid']=$address['id'];
					$group['address']=$address;
					break;
				}
			}
			if(!$group['addressid']){
				$group['addressid']=$member_address['0']['id'];
				$group['address']=$member_address['0'];
			}
		}
		*/
		//整理收货地址信息
		$member_address=pdo_getall('core_address',array('mid'=>$_SESSION['uid']));
		if($member_address){
			foreach($member_address as &$address){
				$address['pcd']=json_decode($address['pcd'],true);
				if($address['isdefault']){
					$item['addressid']=$address['id'];
					$item['address']=$address;
					break;
				}
			}
			if(!$item['addressid']){
				$item['addressid']=$member_address['0']['id'];
				$item['address']=$member_address['0'];
			}
		}
		$this->session('teamid',$teamid);
		$this->session('goodsid',$goodsid);
		$this->session('groupid',$groupid);
		$this->session('type',$type);
		$this->session('heads',$heads);
		$return['address']=$address;
		$return['isverify']=$isverify;
		$return['member']=$member;
		$return['goods']=$goods;
		$return['heads']=$heads;
		$return['group']=$group;
		$return['price']=$price;
		$return['stores']=$stores;
		$return['is_team']=$is_team;
		$return['item']=$item;
		$return['post']=array('sendtype'=>$item['sendtype'],'realname'=>$member['nickname'],'mobile'=>$member['mobile']);
		$return['post']['setno_paytype']=str_array($group['no_paytype']);
		exi($return);
}

if($_RQ['op']=='submit'){
	$mid = $_SESSION['uid'];
	$uniacid = $_SESSION['uniacid'];
	$isverify = false;
	$teamid = $this->session('teamid');
	$goodsid = $this->session('goodsid');
	$groupid = $this->session('groupid');
	$type = $this->session('type');
	$heads = $this->session('heads');
	$member = cfc('core')->member_show($mid);
	$credit = array();
	$group=pdo_get('jy_aligroup_groups',array('uniacid'=>$_SESSION['uniacid'],'id'=>$groupid));
	$goods = pdo_fetch('select * from ' . tablename('jy_weishop_goods') . "\n\t\t\t\t" . 'where id = :id and uniacid = :uniacid order by paixu desc', array(':id' => $goodsid, ':uniacid' => $uniacid));
	if ($type == 'groups') {
			if(!$group['feetype'] && $group['agio']!=0){
				$goods['groupsprice'] = $group['agio']*$goods['price']/100;
			}elseif($group['feetype'] && $group['price']!=0){
				$goods['groupsprice'] = $group['price'];
			}else{
				$goods['groupsprice'] =$goods['price'];
			}
			$goodsprice = $goods['groupsprice'];
			$price = $goods['groupsprice'];
			$groupnum = intval($goods['groupnum']);
			$is_team = 1;
			if(!$teamid){//非参团
				
			}
	}else if ($type == 'single') {
			$goodsprice = $goods['price'];
			$price = $goods['singleprice'];
			$groupnum = 1;
			$is_team = 0;
			$teamid = 0;
	}
			//团长优惠
	if($group['isdiscount']==1 && $heads==1){
			if($group['headstype']==0){
				$goods['headsmoney'] = $group['headsmoney'];
				
			}else{
				$goods['headsmoney'] = $goods['groupsprice'] * $group['headsdiscount']/100;
				
			}
	}
	if($goods['headsmoney']>0){
			$price = $price - $goods['headsmoney'];
	}

	if ($price < 0) {
			$price = 0;
	}

	if ($goods['isverify'] || $goods['type']) {
			$isverify = true;
			$goods['freight'] = 0;
			$storeids = array();
			$merchid = 0;
			if (!(empty($goods['storeids']))) {
				$merchid = $goods['merchid'];
				//$storeids = array_merge(explode(',', $goods['storeids']), $storeids);
				$storeids = json_decode($goods['storeids'],true);
				$ids=array();
				foreach($storeids as $row){
					array_push($ids,$row['id']);
				}
			}
			$params=array('uniacid' => $_SESSION['uniacid'],'status'=>1,'type'=>array(2,3));
			if (empty($storeids)) {
			}else if (0 < $merchid) {
				if($ids){
					$params['id']=$ids;
				}
			} else {
				if($ids){
					$params['id']=$ids;
				}
			}
			$stores = pdo_getall('jy_weishop_store',$params);
			$verifycode = 'PT' . random(8, true);

			while (1) {
				$count = pdo_fetchcolumn('select count(*) from ' . tablename('jy_aligroup_groups_order') . ' where verifycode=:verifycode and uniacid=:uniacid limit 1', array(':verifycode' => $verifycode, ':uniacid' => $_SESSION['uniacid']));
				if ($count <= 0) {
					break;
				}
				$verifycode = 'PT' . random(8, true);
			}
			$verifynum=$goods['verifytype']?$goods['verifynum']:1;
		}else {
			$address = pdo_fetch('select * from ' . tablename('jy_weishop_address') . "\n\t\t\t\t" . 'where mid=:mid and deleted=0 and isdefault=1  and uniacid=:uniacid limit 1', array(':uniacid' => $uniacid, ':mid' => $mid));
		}		
		if($_RQ['postdata']){
			$postdata=get_postdata();
			if(!$postdata){
				exi('请将信息填写完整','error');
			}elseif($postdata){
				if ($postdata['sendtype']==2 && (empty($postdata['realname']) || empty($postdata['mobile']))) {
					exi('联系人或联系电话不能为空！','error');
				}
				if ((0 < intval($postdata['aid'])) && !($isverify)) {
					$order_address = pdo_fetch('select * from ' . tablename('core_address') . ' where id=:id and mid=:mid and uniacid=:uniacid   limit 1', array(':uniacid' => $uniacid, ':mid' => $mid, ':id' => intval($postdata['aid'])));
					if (empty($order_address)) {
						exi('未找到地址','error');
					}
				}
				if($postdata['sendtype']==1 && intval($postdata['aid'])==0){
					exi('请选择收货地址！','error');
				}
				$data = array(
					'uniacid' => $_SESSION['uniacid'],
					'groupnum' => $groupnum, 
					'mid' => $mid, 
					'paytime' => '',
					'orderno' =>get_ordersn('jy_aligroup_groups_order','orderno'),
					'credit' => (intval($_RQ['isdeduct']) ? $_RQ['credit'] : 0),
					'creditmoney' => (intval($_RQ['isdeduct']) ? $_RQ['creditmoney'] : 0),
					'price' => $price, 
					'freight' => $goods['freight'],
					'status' => 0, 
					'goodsid' => $goodsid,
					'groupid' => $groupid,
					'teamid' => $teamid,
					'is_team' => $is_team,
					'heads' => $heads,
					'headsid' => pdo_getcolumn('jy_aligroup_groups_team',array('id'=>$teamid),'headsid'),
					'discount' => (!(empty($heads)) ? $goods['headsmoney'] : 0),
					'addressid' => intval($postdata['aid']),
				//	'address' =>$order_address,
					'message' => trim($postdata['message']),
					'realname' => ($isverify ? trim($postdata['realname']) : ''),
					'mobile' => ($isverify ? trim($postdata['mobile']) : ''),
					'endtime' => $goods['endtime'], 
					'isverify' => intval($goods['isverify']), 
					'verifytype' => intval($goods['verifytype']),
					'verifycode' => $verifycode?$verifycode: 0,
					'verifynum' => $verifynum?$verifynum: 1,
					'createtime' => TIMESTAMP
				);					
				$order_insert = pdo_insert('jy_aligroup_groups_order', $data);
				if (!($order_insert)) {
					exi('生成订单失败！','error');
				}
				$orderid = pdo_insertid(); 
				$params['fee']=$price;
				$params['title']='拼团';
				$params['id']=$orderid;
				$params['plugin']='jy_aligroup';
				$params['back_url']='jy_aligroup/confirm/payresult';
				if($postdata['setno_paytype']){
					$params['no_type']=$postdata['setno_paytype'];
				}
				$payid=cfc('pay')->create_pay_order($params);
				$this->pdo_update('groups_order',array('pay_id'=>$payid),array('id'=>$orderid));
				$return['pay_id']=$payid;
				$return['order_id']=$orderid;
				exi($return);
			}
		}
		$return['address']=$address;
		$return['isverify']=$isverify;
		$return['member']=$member;
		$return['goods']=$goods;
		$return['heads']=$heads;
		$return['group']=$group;
		$return['price']=$price;
		$return['stores']=$stores;
		$return['is_team']=$is_team;
		$return['post']=array();
		exi($return);
}
if($_RQ['op']=='payresult'){
	$payresult=$_RQ['pay_result'];
	if(!$payresult){
		exi('支付失败，未收到支付结果！','error','list');
	}
	$order=pdo_get('jy_aligroup_groups_order',array('id'=>$payresult['id'],'uniacid'=>$_SESSION['uniacid']));
	pdo_update('jy_aligroup_groups_order',array('status'=>1,'paytime'=>TIMESTAMP,'pay_type'=>$payresult['pay_type']),array('id'=>$order['id']));
	if(!$order['teamid'] && $order['is_team']){//参团
			$insertdata=array(
						'uniacid'=>$_SESSION['uniacid'],
						'groupid'=>$order['groupid'],
						'goodsid'=>$order['goodsid'],
						'headsid'=>$_SESSION['uid'],
						'createtime'=>TIMESTAMP
			);
			pdo_insert('jy_aligroup_groups_team',$insertdata);
			$teamid=pdo_insertid();
			pdo_update('jy_aligroup_groups_order',array('teamid'=>$teamid),array('id'=>$order['id']));
	}
	//支付成功，判断拼团人数是否达到，人数达到则更改所有该拼团订单的状态
	$num=pdo_count('jy_aligroup_groups_order',array('uniacid'=>$_SESSION['uniacid'],'status'=>1,'groupid'=>$order['groupid'],'teamid'=>$order['teamid']));
	$group=pdo_get('jy_aligroup_groups',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['groupid']));
	if($group['groupnum']==$num){
		pdo_update('jy_aligroup_groups_team',array('status'=>1),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['teamid']));
		$data=array(
			'status'=>2,
			'success'=>3,
			'finishtime'=>TIMESTAMP
		);
		$orders=pdo_getall('jy_aligroup_groups_order',array('uniacid'=>$_SESSION['uniacid'],'groupid'=>$order['groupid'],'teamid'=>$order['teamid'],'status'=>'1'));
		foreach($orders as $item){
			pdo_update('jy_aligroup_groups_order',$data,array('id'=>$item['id']));
		}
		exi('支付成功','success','jy_aligroup/order/main/status=2');
	}
	exi('支付成功','success','jy_aligroup/order/main/status=1');
}	

